package org.pay.manage.secruity;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.entity.SysResource;
import org.pay.core.entity.SysUser;
import org.pay.manage.common.service.RpcCommonService;
import org.pay.manage.sys.service.SysUserService;

import java.util.LinkedList;
import java.util.List;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RpcCommonService rpcCommonService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findByUserName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(String.format("未找到该用户名下的用户 '%s'.", username));
        } else {
            // 得到用户的权限资源
            List<SysResource> sysResourceList = rpcCommonService.rpcSysService.selectResourceByUserId(sysUser.getUserId());
            List<GrantedAuthority> grantedAuthorities = new LinkedList<>();
            if(CollectionUtils.isNotEmpty(sysResourceList)) {
                for(SysResource sysResource : sysResourceList) {
                    if(sysResource == null) continue;
                    if(StringUtils.isBlank(sysResource.getPermName())) continue;
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysResource.getPermName());
                    grantedAuthorities.add(grantedAuthority);
                }
            }

            // 临时使用,兼容之前的权限
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(MchConstant.MGR_ROLE_NORMAL);
            grantedAuthorities.add(grantedAuthority);

            return JwtUserFactory.create(username, sysUser, grantedAuthorities);
        }
    }
}
